<?php 
/*
 module:		日志管理控制器
 create_time:	2024-06-15 09:04:29
 author:		your name
 contact:		your email address
*/

namespace app\admin\controller\Admin;
use think\exception\ValidateException;
use app\admin\model\Admin\Log as LogModel;
use app\admin\controller\Admin;
use think\facade\Db;

class Log extends Admin {


	/*
	* @Description  数据列表
	*/
	public function index(): \think\response\Json 
	{
		// 分页参数
		$limit  = $this->request->post('limit', 20, 'intval');
		$page = $this->request->post('page', 1, 'intval');

		// 构建查询条件
		$where = [];
		$where['username'] = ['like',$this->request->post('username', null, 'serach_in')];
		$where['ip'] = ['like',$this->request->post('ip', null, 'serach_in')];
		$where['city'] = ['like',$this->request->post('city', null, 'serach_in')];
		$where['type'] = $this->request->post('type', null, 'serach_in');

		$create_time = $this->request->post('create_time', null, 'serach_in');
		if($create_time){
			$start = date('Y-m-d H:i:s',strtotime(date('Y-m-d',strtotime($create_time)).' 00:00:00'));
			$end = date('Y-m-d H:i:s',strtotime(date('Y-m-d',strtotime($create_time)).' 23:59:59'));
			$where['create_time'] = ['between',[$start,$end]];
		}

		//  查询的字段
		$field = 'id,application_name,username,url,ip,city,useragent,content,errmsg,type,sort_id,status,create_time,update_time';

		//  执行查询操作
		try{
			$res = LogModel::field($field)
				->where(formatWhere($where))
				->whereRaw($this->whereScope())
				->order('id desc')
				->paginate(['list_rows'=>$limit,'page'=>$page])
				->toArray();
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		$data['status'] = 200;
		$data['data'] = $res;
		return json($data);
	}


	/*
 	* @Description  修改排序开关
 	*/
	public function updateExt(): \think\response\Json 
	{
		$data = $this->request->post();
		if(!$data['id']) throw new ValidateException ('参数错误');
		LogModel::update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}

	/*
 	* @Description  删除
 	*/
	public function delete(): \think\response\Json 
	{
		$idx =  $this->request->post('id', null, 'serach_in');
		if(!$idx) throw new ValidateException ('参数错误');
		LogModel::destroy(['id'=>explode(',',$idx)],true);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/*
 	* @Description  查看详情
 	*/
	public function detail(): \think\response\Json 
	{
		//  组织提交的数据
		$id =  $this->request->post('id', null, 'serach_in');
		if(!$id) throw new ValidateException ('参数错误');
		$field = 'id,application_name,username,url,ip,city,useragent,content,errmsg,type,sort_id,status,create_time,update_time';
		$res = LogModel::field($field)->find($id)->toArray();
		return json(['status'=>200,'data'=>$res]);
	}


	/*
 	* @Description  导出
 	*/
	public function exportData(): \think\response\Json 
	{
		try{
			$data = $this->request->post();
			// 初始化对象
			$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
			// 获取活动工作簿
			$sheet = $spreadsheet->getActiveSheet();
			// 定义标题
			if($data['isHeader']){
				foreach ($data['columns'] as $k => $v){
					$sheet->setCellValue([$k + 1, 1], $v['title']);
				}
			}
			// 根据模式查询数据
			if($data['mode'] == 'all'){
				$dataList = LogModel::select()
					->toArray();
			} else {
				$dataList = LogModel::where(['id'=>$data['data']])
					->select()
					->toArray();
			}
			// 构造选项数据
			foreach($dataList as $key=>$val){
				$dataList[$key]['type'] = getItemVal($val['type'],'[{"label":"登录日志","value":"1","label_color":"success"},{"label":"操作日志","value":"2","label_color":"warning"},{"label":"异常日志","value":"3","label_color":"danger"}]');
				$dataList[$key]['status'] = getItemVal($val['status'],'[{"label":"开启","value":"1","label_color":"primary"},{"label":"关闭","value":"0","label_color":"danger"}]');
			}
			// 构造数据
			foreach ($dataList as $k => $v){
				foreach ($data['columns'] as $_k => $_v){
					if(strpos($_v['field'],'.')){
						$key = explode('.',$_v['field']);
						$sheet->setCellValue([$_k + 1,$k + 2],$v[$key[0]][$key[1]]);
					} else {
						// 对全部都是数字的单元格进行强制转换为字符串
						if(preg_match('/^[0-9]*$/',$v[$_v['field']])){
							$sheet->setCellValueExplicit([$_k + 1,$k + 2],$v[$_v['field']],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
						} else {
							$sheet->setCellValue([$_k + 1,$k + 2],$v[$_v['field']]);
						}
					}
				}
			}
			$filename =   $data['filename'] . '.' . $data['type'];
			header('Access-Control-Allow-Origin:*');
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment;filename="' . $filename . '"');
			header('Cache-Control: max-age=0');
			$res_excel = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, ucfirst($data['type']));
			ob_start();
			$res_excel->save('php://output');
			$xlsData = ob_get_contents();
			ob_end_clean();
			$data = ['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)];
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return json(['status'=>200,'data'=>$data]);
	}


	/*
 	* @Description  获取定义sql语句的字段信息
 	*/
	public function getFieldList(): \think\response\Json 
	{
		return json(['status'=>200,'data'=>$this->getSqlField('',)]);
	}

	/*
 	* @Description  获取定义sql语句的字段信息
 	*/
	private function getSqlField($list): array 
	{
		$data = [];
		return $data;
	}


	

}

